#ifndef __MEMPOOL_H__
#define __MEMPOOL_H__

#include "RecycleQueue.h"

#include<iterator>
#include<iostream>
#include<unistd.h>
#include<ext/hash_map>
#include<assert.h>



#define SYSTEM_LEVEL 0x01
#define THREAD_LEVEL 0x02
#define CONNECTION_LEVEL 0x04

#define MEM_ELEM_HEAD_LEN sizeof(struct mempool_elem)

#define INIT_NODE(x) do{  \
		(x)->addr = NULL; \
		(x)->size = 0;   \
		(x)->next = NULL; \
	}while(0)

/*
 * 管理节点;
 */
struct Node_t{
	void * addr;
	int size;
	struct Node_t *next;
};

struct MemHead_st{
	struct Node_t * queueHead;
	int count;
	struct Node_t * queueTail;
};



//内存池的上下文;
struct mempool_ctx{	
	unsigned int allocated; //已经从堆栈获取的字节数;
	int level; //对内存池进行级别性区分;
	//小内存块链表;
	int count; //计数器;
	struct mempool_elem *head;
	struct mempool_elem *tail;
	//内存块的回收机制;
	struct MemHead_st queue;
	__gnu_cxx::hash_map<int , struct Node_t * >  largeMem;
	__gnu_cxx::hash_map<int , struct Node_t * >  freeMem;
};


//内存池的元素;
struct mempool_elem{
	int index;
	bool isFull; //是否已经用完的标志位;
	char * startaddr; //起始地址;
	char * curraddr; //剩余内存块的地址;
	int pageSize; //内存块的大小;
	int usedSize; //已经使用掉的; 
	struct mempool_elem *next;  //下一级指针;
	struct mempool_elem *prev;  //上一级指针;
};

const int sysTemMemPageSize = sysconf(_SC_PAGESIZE); //本机是4096;


//内存池类;
class MemPool
{
	public:
		MemPool();
		~MemPool();
		int init(int);
		void * allocateMemFromMempool(int size);
		int freeMemaddr(void *addr, int size);
	private:
		struct mempool_ctx ctx; //内存池的上下文;

};




#endif 
